package com.jkhan.demo.ioflow.protocol;

import org.junit.Test;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

/**
 * @ClassName UDPTest
 * @Description UDPTest
 * @Author hjk
 * @Date 2022/2/27 15:49
 **/
public class UDPTest {

    @Test
    public void sender() {
        DatagramSocket datagramSocket = null;
        try {
            InetAddress inetAddress = InetAddress.getByName("127.0.0.1");
            String str = "UDP方式发送的数据报";
            byte[] data = str.getBytes();

            datagramSocket = new DatagramSocket();
            DatagramPacket datagramPacket = new DatagramPacket(data, 0, data.length, inetAddress, 9090);

            datagramSocket.send(datagramPacket);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (datagramSocket != null) {
                datagramSocket.close();
            }
        }

    }

    @Test
    public void receiver() {
        DatagramSocket datagramSocket = null;

        try {
            datagramSocket = new DatagramSocket(9090);

            byte[] buffer = new byte[100];
            DatagramPacket datagramPacket = new DatagramPacket(buffer, 0, buffer.length);
            datagramSocket.receive(datagramPacket);

            System.out.println(new String(datagramPacket.getData(), 0, datagramPacket.getLength()));
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (datagramSocket != null) {
                datagramSocket.close();
            }
        }
    }
}
